//
//  ProvinciaController.m
//  Futbol5Final
//
//  Created by Johan Chaves on 4/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ProvinciaController.h"

@implementation ProvinciaController

@synthesize provincias;

- (void) startLoading{
    
    provincias = [[NSMutableArray alloc]init];
    
    responseData = [[NSMutableData data] retain];
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/futbol/provincia/getAll"]];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];

}

- (void) setListener:(com_digitalart_futbol5_mobileMasterViewController *)listener{
    listenerForJason = listener;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	//label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
    NSLog(@"error %@",[error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
    
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	[responseData release];
    
	provinciasData = [responseString JSONValue];
    
    [self loadProvincias];
}


- (void)loadProvincias
{    
    NSMutableDictionary *provinciaTmp = [[NSMutableDictionary alloc]init];
    
    ProvinciaVO *provinciaVoTmp;
    
    NSString *ids;
    
    NSEnumerator *arrenum = [provinciasData objectEnumerator];
    id cobj;   
    
    while ( cobj = [arrenum nextObject] ) {
        
        [provinciaTmp setDictionary:cobj];
        ids = [provinciaTmp objectForKey:@"id_provincia"];
        
        provinciaVoTmp = [[ProvinciaVO alloc]initWithData:[provinciaTmp objectForKey:@"cantones"]:[provinciaTmp objectForKey:@"nombre"] :UITableViewCellStyleDefault :[ids intValue] reuseIdentifier:@"provincia"];            
        
        [provincias addObject:provinciaVoTmp];
        
        [provinciaVoTmp release];
        [ids release];
    }  
    
    [provinciaTmp release];
    [cobj release];
    
    [listenerForJason updateTable];
    
}


@end
